package org.calzz.example;

import org.apache.commons.lang.StringEscapeUtils;
import org.calzz.jajb.JsonDeserializer;
import org.calzz.jajb.JsonSerializer;
import org.calzz.jajb.converter.IConverter;
import org.calzz.jajb.io.IWriter;
import org.springframework.core.MethodParameter;

public class EscapeHtmlStringConverter implements IConverter {

	@Override
	public boolean canConvert(Class<?> clazz) {
		return String.class.equals(clazz) || Character.class.equals(clazz);
	}

	@Override
	public void marshal(Object obj, String name, IWriter writer, JsonSerializer
		serializer) {
		writer.writeKey(name);
		writer.writeString(StringEscapeUtils.escapeHtml(obj.toString()));
	}

	@Override
	public <T> Object unmarshal(Object env, Class<T> clazz, JsonDeserializer
		deserializer, MethodParameter methodParam) {
		String value = StringEscapeUtils.unescapeHtml(env.toString());

		if (Character.class.equals(clazz) || char.class.equals(clazz)) {
			return value.charAt(0);
		}
		return value;
	}
}